package com.lantu.draw.svgimg.action;

import com.lantu.draw.framework.BaseAction;
import com.lantu.draw.login.MD5Encrypt;
import com.lantu.draw.svgimg.service.SVGFavoriteService;
import com.lantu.draw.svgimg.service.SVGImageService;
import com.lantu.draw.svgimg.vo.SVGFavoriteVO;
import com.lantu.draw.svgimg.vo.SVGPaintIconVO;
import com.lantu.draw.svgimg.vo.SVGPaintVO;
import com.lantu.image.UploadTool;
import com.lantu.transcoder.SaveAsJPEG;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
@Results( { 
	@Result(name = "selectCodeInfo", type = "json", params = { "root", "codeInfoVO" }),
	@Result(name = "successjson", type = "json", params = { "root", "result" }),
	@Result(name = "success", type = "json", params = { "root", "msg" }),
	@Result(name = "loadCodeTypeName", type = "json", params = { "root", "nodeList" }),
	@Result(name = "page", location = "mysvg/page.html"),
	@Result(name = "error", location = "error.jsp", type = "dispatcher"),
	@Result(name = "input",type = "json", params = { "root", "replyMap" })
})
public class SvgImageAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(SvgImageAction.class);
	private final static int CONSTANT_PAGESIZE=4;
	@Resource
	private SVGImageService svgimageService;
	@Resource
	private SVGFavoriteService favoriteService;

	private SVGPaintVO svgimagevo;
	private List result;
	private String base64;
	private float width;
	private float height;
	public float getWidth() {
		return width;
	}
	public void setWidth(float width) {
		this.width = width;
	}
	public float getHeight() {
		return height;
	}
	public void setHeight(float height) {
		this.height = height;
	}
	
	public String getBase64() {
		return base64;
	}
	public void setBase64(String base64) {
		this.base64 = base64;
	}
	private Map<String, Object> msg;  
	  
	private double leftX;
	private double topY;
	
	public double getLeftX() {
		return leftX;
	}
	public void setLeftX(double leftX) {
		this.leftX = leftX;
	}
	public double getTopY() {
		return topY;
	}
	public void setTopY(double topY) {
		this.topY = topY;
	}
	public Map<String, Object> getMsg() {  
	      return msg;  
	}  
	public List getResult() {
		return result;
	}
	public void setResult(List result) {
		this.result = result;
	}
	public SVGPaintVO getSvgimagevo() {
		return svgimagevo;
	}
	public void setSvgimagevo(SVGPaintVO svgimagevo) {
		this.svgimagevo = svgimagevo;
	}
	@Action("/getsvg")
	public String getsvg(){
		SVGPaintVO paintvo=svgimageService.queryPaintByPaintId(svgimagevo.getId());
		msg = new HashMap<String, Object>(); 
		msg.put("svg", paintvo.getSvg());
		return SUCCESS;
	}
	@Action("/savesvg")  
	public String savesvg(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		/*http://techslides.com/save-svg-as-an-image
		 * https://github.com/d3/d3/wiki/API--%E4%B8%AD%E6%96%87%E6%89%8B%E5%86%8C
		 * */
		//String fileUrl = UploadTool.upload(base64);
        //System.out.println("上传文件路径是：" + fileUrl);
		
		HttpSession session=ServletActionContext.getRequest().getSession();
		msg = new HashMap<String, Object>(); 
		String svg=svgimagevo.getSvg();
		if(session.getAttribute("userid")==null||session.getAttribute("userid").equals("null")){
			msg.put("code", "0");
			msg.put("desc", "未登录");
			return SUCCESS;
		}
		if(svg!=null&&svg.trim().equals("")){
			msg.put("code", "0");
			msg.put("desc", "非法保存,数据为空字符");
			return SUCCESS;
		}
		svgimagevo.setUsrId((String)session.getAttribute("userid"));
		 String fileName = "icon_"+UUID.randomUUID().toString()+System.currentTimeMillis()+".jpg";
		svgimagevo.setFileName(fileName);
		
		svgimagevo.setSvg(svgimagevo.getSvg().replaceAll("^<svg id=\"SvgjsSvg[0-9a-zA-Z\"\\s%=/:.]*>","")
				.replaceAll("<defs id=\"SvgjsDefs[0-9\"\\s]*></defs>","")
				.replace("</svg>",""));
		svgimagevo.setIdcard(MD5Encrypt.encode(fileName+":"+svgimagevo.getUsrId()));
		svgimageService.savesvg(svgimagevo);
		
		SaveAsJPEG.svg2Jpeg(svg,fileName,leftX,topY,width,height);
		
		msg.put("code", "1");
		msg.put("desc", "成功");

		return SUCCESS;
	}
	@Action("/mypaint")   
	public String mypaint(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		int pageno=Integer.valueOf(request.getParameter("pageno"));
		if(pageno==0) pageno=1;
		SVGPaintVO qo=new SVGPaintVO();
		qo.setStart((pageno-1)*18);
		qo.setPagesize(18);
		result=svgimageService.queryPaintByUsrId((String)session.getAttribute("userid"),qo);
		return "successjson";
	}
	@Action("/myicon")   
	public String myicon(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		HttpSession session=ServletActionContext.getRequest().getSession();
		HttpServletRequest request=ServletActionContext.getRequest();
		int pageno=Integer.valueOf(request.getParameter("pageno"));
		if(pageno==0) pageno=1;
		SVGPaintIconVO qo=new SVGPaintIconVO();
		
		if(session.getAttribute("userid")==null||session.getAttribute("userid").equals("null")){
			qo.setUsrId(null);
		}else{
			String userid=(String)session.getAttribute("userid");
			qo.setUsrId(userid);
		}
		qo.setStart((pageno-1)*20);
		
		result=svgimageService.queryIconByUsrId((String)session.getAttribute("userid"),qo);
		return "successjson";
	}
	@Action("/shareicon")   
	public String shareicon(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		HttpServletRequest request=ServletActionContext.getRequest();
		SVGPaintIconVO qo=new SVGPaintIconVO();
		int pageno=Integer.valueOf(request.getParameter("pageno"));
		if(pageno==0) pageno=1;
		qo.setStart((pageno-1)*20);
		HttpSession session=ServletActionContext.getRequest().getSession();
		if(session.getAttribute("userid")==null||session.getAttribute("userid").equals("null")){
			qo.setUsrId(null);
		}else{
			String userid=(String)session.getAttribute("userid");
			qo.setUsrId(userid);
		}
		qo.setStart((pageno-1)*20);
		result=svgimageService.queryShareIcon(qo);
		return "successjson";
	}

	@Action("/addfavorite")   
	public String addfavorite(){
		HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
		res.addHeader("Access-Control-Allow-Origin","http://lantudrawing.com");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		res.setHeader("Access-Control-Allow-Credentials","true");
		msg = new HashMap<String, Object>(); 
		HttpSession session=ServletActionContext.getRequest().getSession();
		String imgIdobj=ServletActionContext.getRequest().getParameter("imgId");
		
		String userid=(String)session.getAttribute("userid");
		if(imgIdobj==null||imgIdobj.trim().equals("")){
			msg.put("code", "0");
			msg.put("desc", "参数为空");
			return "successjson";
		}
		int imgId=Integer.valueOf(imgIdobj);
		if(userid==null||userid.trim().equals("")){
			msg.put("code", "0");
			msg.put("desc", "会话不存在");
			return "successjson";
		}
		SVGFavoriteVO vo=new SVGFavoriteVO();
		vo.setFavoriteUsrId((String)session.getAttribute("userid"));
		vo.setImgId(imgId);
		favoriteService.save(vo);
		msg.put("code", "1");
		msg.put("desc", "成功");
		return SUCCESS;
	}
	
	public String error(){
		try{
			throw new Exception();
		}
		catch(Exception e){
			
			return "error";
		}
	}
	public String save(){
		return "successjson";
	}
	public String execute() {
		return SUCCESS;
	}
	
}
